package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.context.SecurityContextHolder;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.system.domain.MoveOrder;
import com.ruoyi.system.domain.MoveOrderInfo;
import com.ruoyi.system.domain.WarehouseOrderInfo;
import com.ruoyi.system.mapper.MoveOrderMapper;
import com.ruoyi.system.mapper.WarehouseOrderInfoMapper;
import com.ruoyi.system.mapper.WarehouseOrderMapper;
import com.ruoyi.system.service.IMoveOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 移库单Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-02-11
 */
@Service
public class MoveOrderServiceImpl implements IMoveOrderService 
{
    @Autowired
    private MoveOrderMapper moveOrderMapper;

    /**
     * 查询移库单
     * 
     * @param id 移库单主键
     * @return 移库单
     */
    @Override
    public MoveOrder selectMoveOrderById(Long id)
    {
        return moveOrderMapper.selectMoveOrderById(id);
    }

    /**
     * 查询移库单列表
     * 
     * @param moveOrder 移库单
     * @return 移库单
     */
    @Override
    public List<MoveOrder> selectMoveOrderList(MoveOrder moveOrder)
    {
        return moveOrderMapper.selectMoveOrderList(moveOrder);
    }

    /**
     * 新增移库单
     * 
     * @param moveOrder 移库单
     * @return 结果
     */
    @Transactional
    @Override
    public int insertMoveOrder(MoveOrder moveOrder)
    {
        String userName = SecurityContextHolder.getUserName();
        moveOrder.setCreateOrderUser(userName);
        moveOrder.setCreateTime(DateUtils.getNowDate());
        int rows = moveOrderMapper.insertMoveOrder(moveOrder);
        insertMoveOrderInfo(moveOrder);
        return rows;
    }

    /**
     * 修改移库单
     * 
     * @param moveOrder 移库单
     * @return 结果
     */
    @Transactional
    @Override
    public int updateMoveOrder(MoveOrder moveOrder)
    {
        moveOrderMapper.deleteMoveOrderInfoByMoveOrderId(moveOrder.getId());
        insertMoveOrderInfo(moveOrder);
        return moveOrderMapper.updateMoveOrder(moveOrder);
    }

    /**
     * 批量删除移库单
     * 
     * @param ids 需要删除的移库单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteMoveOrderByIds(Long[] ids)
    {
        moveOrderMapper.deleteMoveOrderInfoByMoveOrderIds(ids);
        return moveOrderMapper.deleteMoveOrderByIds(ids);
    }

    /**
     * 删除移库单信息
     * 
     * @param id 移库单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteMoveOrderById(Long id)
    {
        moveOrderMapper.deleteMoveOrderInfoByMoveOrderId(id);
        return moveOrderMapper.deleteMoveOrderById(id);
    }

    /**
     * 新增移库单明细信息
     * 
     * @param moveOrder 移库单对象
     */
    public void insertMoveOrderInfo(MoveOrder moveOrder)
    {
        List<MoveOrderInfo> moveOrderInfoList = moveOrder.getMoveOrderInfoList();
        Long id = moveOrder.getId();
        if (StringUtils.isNotNull(moveOrderInfoList))
        {
            List<MoveOrderInfo> list = new ArrayList<MoveOrderInfo>();
            List<WarehouseOrderInfo> warehouseOrderInfoList = new ArrayList<WarehouseOrderInfo>();
            for (MoveOrderInfo moveOrderInfo : moveOrderInfoList)
            {
                moveOrderInfo.setMoveOrderId(id);
                list.add(moveOrderInfo);

                WarehouseOrderInfo warehouseOrderInfo = new WarehouseOrderInfo();
                warehouseOrderInfo.setProductId(moveOrderInfo.getProductId());
                warehouseOrderInfo.setWarehousePositionId(moveOrderInfo.getOriginalWarehouseId());
                warehouseOrderInfo.setNum(moveOrderInfo.getNum());
                warehouseOrderInfoList.add(warehouseOrderInfo);
            }
            if (list.size() > 0)
            {
                moveOrderMapper.batchMoveOrderInfo(list);
            }

            //1、产品的原库位做出库操作
            //更新入库产品库存（入库产品数量-出库数量）
            if (warehouseOrderInfoList.size() > 0)
            {
                moveOrderMapper.batchUpdateWarehouseOrderInfo(warehouseOrderInfoList);
            }
            //2、产品的新库位做入库操作
              saveWarehouseOrderInfo(list);
        }
    }


    @Autowired
    private WarehouseOrderInfoMapper warehouseOrderInfoMapper;

    private void saveWarehouseOrderInfo(List<MoveOrderInfo> list) {
        for (MoveOrderInfo moveOrderInfo : list) {
//            在入库明细新增一条明细：产品 库位 数量 所属入库单（原产品所在入库单）
//            如果该产品在该库位已经存在入库明细，只是修改数量
            //先根据产品id和库位id查询入库明细，如果存在，修改数量，不存在，新增一条入库明细
            WarehouseOrderInfo warehouseOrderInfo = warehouseOrderInfoMapper.selectWarehouseByPidAndWpid(moveOrderInfo);
            if(warehouseOrderInfo==null){
                // 没查到，新增
                warehouseOrderInfo = new WarehouseOrderInfo();
                warehouseOrderInfo.setProductId(moveOrderInfo.getProductId());
                warehouseOrderInfo.setProductName(moveOrderInfo.getProductName());
                warehouseOrderInfo.setProductCode(moveOrderInfo.getProductCode());
                warehouseOrderInfo.setBatch(moveOrderInfo.getBatchNo());
                warehouseOrderInfo.setPrice(moveOrderInfo.getUnitPrice());
                warehouseOrderInfo.setNum(moveOrderInfo.getNum());

                // 计算 totalPrice
                BigDecimal unitPrice = moveOrderInfo.getUnitPrice();
                BigDecimal num = new BigDecimal(moveOrderInfo.getNum());
                BigDecimal totalPrice = unitPrice.multiply(num);
                warehouseOrderInfo.setTotalPrice(totalPrice);

                warehouseOrderInfo.setWarehousePositionId(moveOrderInfo.getTargetWarehouseId());
                WarehouseOrderInfo warehouseOrderInfoOld = warehouseOrderInfoMapper.selectOldWarehouseByPidAndWpid(moveOrderInfo);
                warehouseOrderInfo.setWarehouseOrderId(warehouseOrderInfoOld.getWarehouseOrderId());//原库为入库单

            } else {
                // 查到，修改数量和总价
                Long newNum = warehouseOrderInfo.getNum() + moveOrderInfo.getNum();
                warehouseOrderInfo.setNum(newNum);

                // 计算新的 totalPrice
                BigDecimal unitPrice = moveOrderInfo.getUnitPrice();
                BigDecimal newNumBigDecimal = new BigDecimal(newNum);
                BigDecimal newTotalPrice = unitPrice.multiply(newNumBigDecimal);
                warehouseOrderInfo.setTotalPrice(newTotalPrice);
            }

            // 保存或更新 WarehouseOrderInfo
            if (warehouseOrderInfo.getId() == null) {
                warehouseOrderInfoMapper.insertWarehouseOrderInfo(warehouseOrderInfo);
            } else {
                warehouseOrderInfoMapper.updateWarehouseOrderInfo(warehouseOrderInfo);
            }
        }
    }
}
